<template>
  <div class="chat-container">
    <!-- 顶部导航 -->
    <van-nav-bar
      :title="targetUserInfo.userName"
      left-arrow
      @click-left="router.back()"
      fixed
      class="chat-header"
      :border="false"
    >
      <template #left>
        <van-icon name="arrow-left" size="20" color="#666"/>
      </template>
    </van-nav-bar>

    <!-- 消息列表区域 -->
    <div class="message-list" ref="messageListRef">
      <div class="message-date-wrapper" v-if="messages.length">
        <span class="message-date">{{ formatDate(messages[0].timestamp) }}</span>
      </div>

      <div 
        v-for="(msg, index) in messages" 
        :key="msg.id"
        class="message-wrapper"
      >
        <div class="message-date-wrapper" v-if="shouldShowTime(msg, messages[index-1])">
          <span class="message-date">{{ formatDate(msg.timestamp) }}</span>
        </div>
        
        <div 
          class="message-item"
          :class="{ 'message-mine': msg.fromId === currentUserId }"
        >
          <div class="user-info" :class="{ 'user-info-right': msg.fromId === currentUserId }">
            <van-image
              round
              width="40"
              height="40"
              :src="msg.avatar || defaultAvatar"
              class="avatar"
            />
          </div>
          
          <div class="message-content">
            <div class="message-text">{{ msg.content }}</div>
            <div class="message-status" v-if="msg.fromId === currentUserId">
              <van-loading v-if="msg.sending" type="spinner" size="12px" color="#8c8c8c" />
              <van-icon v-else-if="msg.failed" name="warning-o" color="#ee0a24" size="14px" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部输入区域 -->
    <div class="input-area">
      <van-field
        v-model="inputMessage"
        placeholder="请输入消息"
        :border="false"
        class="message-input"
        @keypress.enter="handleSend"
        :autofocus="true"
        maxlength="500"
      >
        <template #button>
          <van-button 
            size="small" 
            type="primary" 
            @click="handleSend"
            :disabled="!inputMessage.trim()"
            :loading="sending"
            round
          >
            发送
          </van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { sendMessage, listenMessages } from '@/utils/chat'
import { tim,TIM } from '@/tim'
import { showToast } from 'vant'

const route = useRoute()
const router = useRouter()

// 基础数据
const messages = ref([])
const inputMessage = ref('')
const messageListRef = ref(null)
const currentUserId = ref('') // 当前用户ID
const chatTitle = ref('聊天')
const defaultAvatar = 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'

// 添加发送状态
const sending = ref(false)

// 添加下刷新状态
const isRefreshing = ref(false)

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  // 今天的消息只显示时间
  if (date.toDateString() === now.toDateString()) {
    return formatTime(timestamp)
  }
  
  // 昨天的消息显示"昨天"
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${formatTime(timestamp)}`
  }
  
  // 其他日期显示完整日期
  return `${date.getMonth() + 1}月${date.getDate()}日 ${formatTime(timestamp)}`
}

// 判断是否需要显示时间
const shouldShowTime = (currentMsg, prevMsg) => {
  if (!prevMsg) return false
  // 如果两条消息间隔超过5分钟，显示时间
  return currentMsg.timestamp - prevMsg.timestamp > 5 * 60 * 1000
}

// 发送消息
const handleSend = async () => {
  if (!inputMessage.value.trim() || sending.value) return
  
  const content = inputMessage.value.trim()
  inputMessage.value = ''
  
  const tempMessage = {
    id: Date.now(),
    content: content,
    fromId: currentUserId.value,
    timestamp: Date.now(),
    type: 'text',
    sending: true,
    toUserName: targetUserInfo.value.userName
  }
  
  messages.value.push(tempMessage)
  scrollToBottom()
  
  try {
    sending.value = true
    
    // 检查登录状态
    const imUser = sessionStorage.getItem('im_user')
    if (!imUser) {
      throw new Error('未登录')
    }

    // 确保 ID 格式正确
    const receiverId = String(route.query.userId).trim()
    if (!receiverId) {
      throw new Error('接收者ID无效')
    }

    const result = await sendMessage({
      toId: receiverId,
      content: content,
      type: 'text',
      toUserName: targetUserInfo.value.userName
    })
    
    if (result.code === 0 && result.data?.message) {
      // 更新消息状态
      const index = messages.value.findIndex(msg => msg.id === tempMessage.id)
      if (index !== -1) {
        messages.value[index] = {
          ...messages.value[index],
          id: result.data.message.ID || tempMessage.id, // 添加后备的 ID
          sending: false,
          failed: false
        }
      }
    } else {
      throw new Error(result.message || '发送失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    showToast('发送失败，请重试')
    const index = messages.value.findIndex(msg => msg.id === tempMessage.id)
    if (index !== -1) {
      messages.value[index] = {
        ...messages.value[index],
        sending: false,
        failed: true
      }
    }
  } finally {
    sending.value = false
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const hours = date.getHours()
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

// 监听新消息
const unsubscribe = ref(null)
onMounted(async () => {
  try {
    // 检查登录状态
    const imUser = sessionStorage.getItem('im_user')
    if (!imUser) {
      throw new Error('未登录')
    }

    // 等待 SDK ready
    await new Promise((resolve, reject) => {
      let timeoutId

      function onSDKReady() {
        clearTimeout(timeoutId)
        tim.off(TIM.EVENT.SDK_READY, onSDKReady)
        tim.off(TIM.EVENT.SDK_NOT_READY, onSDKNotReady)
        resolve()
      }

      function onSDKNotReady() {
        clearTimeout(timeoutId)
        tim.off(TIM.EVENT.SDK_READY, onSDKReady)
        tim.off(TIM.EVENT.SDK_NOT_READY, onSDKNotReady)
        reject(new Error('SDK not ready'))
      }

      // 检查当前登录状态
      tim.getMyProfile().then(profile => {
        if (profile.data?.userID) {
          resolve()
          return
        }
        // 如果未登录，则监听事件
        tim.on(TIM.EVENT.SDK_READY, onSDKReady)
        tim.on(TIM.EVENT.SDK_NOT_READY, onSDKNotReady)
      }).catch(() => {
        // 如果获取 profile 失败，则监听事件
        tim.on(TIM.EVENT.SDK_READY, onSDKReady)
        tim.on(TIM.EVENT.SDK_NOT_READY, onSDKNotReady)
      })

      // 设置超时
      timeoutId = setTimeout(() => {
        tim.off(TIM.EVENT.SDK_READY, onSDKReady)
        tim.off(TIM.EVENT.SDK_NOT_READY, onSDKNotReady)
        reject(new Error('SDK ready 超时'))
      }, 10000)
    })

    // 获取用户信息
    const profile = await tim.getMyProfile()
    if (!profile.data?.userID) {
      throw new Error('获取用户信息失败')
    }
    currentUserId.value = profile.data.userID

    // 确保有接收者ID
    if (!route.query.userId) {
      throw new Error('接收者ID无效')
    }

    // 设置聊天标题
    chatTitle.value = route.query.userName || '聊天'
    
    // 获取历史消息
    await getHistoryMessages()
    
    // 监听新消息
    function onMessageReceived(event) {
      const messageList = event.data
      messageList.forEach((message) => {
        if (message.from === route.query.userId || 
            message.from === currentUserId.value) {
          messages.value.push({
            id: message.ID,
            content: message.payload?.text || '',
            fromId: message.from,
            timestamp: message.time * 1000,
            type: message.type,
            avatar: message.avatar
          })
          scrollToBottom()
        }
      })
    }
    
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived)
    unsubscribe.value = () => {
      tim.off(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived)
    }
  } catch (error) {
    console.error('初始化聊天失败:', error)
    showToast('初始化失败，请重试')
    router.back()
  }
})

// 获取史消息
const getHistoryMessages = async () => {
  try {
    const result = await tim.getMessageList({
      conversationID: `C2C${route.query.userId}`,
      count: 15
    })
    
    messages.value = result.data.messageList.map(msg => ({
      id: msg.ID,
      content: msg.payload?.text || '',
      fromId: msg.from,
      timestamp: msg.time * 1000,
      type: msg.type,
      avatar: msg.avatar
    }))
    
    scrollToBottom()
  } catch (error) {
    console.error('获取历史消息失败:', error)
  }
}

onUnmounted(() => {
  // 清理消息监听
  if (unsubscribe.value) {
    unsubscribe.value()
  }
})

const targetUserInfo = ref({
  userId: route.query.userId,
  userName: route.query.userName || '用户',
  avatar: ''
})

// 获取户资料
const getUserProfile = async () => {
  try {
    const { data } = await tim.getUserProfile({
      userIDList: [targetUserInfo.value.userId]
    })
    
    if (data.length > 0) {
      const userInfo = data[0]
      targetUserInfo.value = {
        userId: userInfo.userID,
        userName: userInfo.nick || userInfo.userID,
        avatar: userInfo.avatar
      }
    }
  } catch (error) {
    console.error('获取用户资料失败:', error)
  }
}

onMounted(() => {
  getUserProfile()
})
</script>

<style scoped>
.chat-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.chat-header {
  background-color: rgba(255, 255, 255, 0.98);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  z-index: 1000;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px 16px;
  padding-top: 56px;
  padding-bottom: 70px;
  -webkit-overflow-scrolling: touch;
}

.message-date-wrapper {
  text-align: center;
  margin: 16px 0;
}

.message-date {
  display: inline-block;
  padding: 4px 12px;
  background-color: rgba(0, 0, 0, 0.06);
  color: #666;
  font-size: 12px;
  border-radius: 16px;
  line-height: 1.4;
}

.message-wrapper {
  margin-bottom: 16px;
  position: relative;
}

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin: 0 8px;
}

.message-mine {
  flex-direction: row-reverse;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  width: 44px;
  flex-shrink: 0;
}

.user-info-right {
  align-items: flex-end;
}

.avatar {
  border: 1px solid rgba(0, 0, 0, 0.05);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  width: 40px !important;
  height: 40px !important;
}

.message-content {
  position: relative;
  max-width: 70%;
  min-width: 40px;
  margin: 0 4px;
  flex: 1;
}

.message-text {
  background-color: #fff;
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 15px;
  line-height: 1.4;
  color: #333;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  word-break: break-word;
  transition: all 0.2s ease;
  display: inline-block;
  max-width: 100%;
}

.message-mine .message-text {
  background-color: #1989fa;
  color: #fff;
  border-bottom-right-radius: 4px;
  float: right;
}

.message-status {
  position: absolute;
  right: -20px;
  bottom: 2px;
  display: flex;
  align-items: center;
  height: 20px;
}

.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(255, 255, 255, 0.98);
  padding: 8px 12px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.05);
  z-index: 1000;
}

.message-input {
  background-color: #f5f5f5;
  border-radius: 24px;
  margin-right: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
}

:deep(.van-field__body) {
  padding: 6px 8px;
  flex: 1;
}

:deep(.van-field__control) {
  min-height: 20px;
  font-size: 15px;
  color: #333;
  padding: 4px 0;
}

:deep(.van-button) {
  height: 32px;
  padding: 0 16px;
  font-size: 14px;
  border-radius: 16px;
  font-weight: 500;
  margin-right: 4px;
}

:deep(.van-nav-bar) {
  height: 46px;
  line-height: 46px;
  position: fixed;
  width: 100%;
  top: 0;
}

:deep(.van-nav-bar__content) {
  height: 46px;
}

:deep(.van-nav-bar__title) {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  line-height: 46px;
}

:deep(.van-nav-bar__left),
:deep(.van-nav-bar__right) {
  height: 46px;
  line-height: 46px;
}

:deep(.van-field__word-limit) {
  display: none;
}
</style>
